﻿using System;
using System.Collections.Generic;
using System.Text;

using System.Net;
using System.IO;
using HAVNet.Core.LitJson;

namespace yiracli
{
    public class Issue
    {
        public string   key     { get; private set; }
        public string   summary { get; private set; }
        public int      total   { get; private set; }
        public int      progress{ get; private set; }
        public int      percent { get; private set; }
        public string status {get; private set; }
        public string priority { get; private set; }

        public static List<Issue> get (Autorizacion auto, string name)
        {
            //string url = string.Format(
            //    "http://sm-jiratest:8080/rest/api/latest/search?jql=Asignados={0}+AND+status+in+(abierto,+reabierto,%22En%20Progreso%22)+order+by+priority",
            //    name
            //);

            string url = string.Format(
                "http://sm-jiratest:8080/rest/api/latest/search?jql=Asignados={0}",
                name
            );

            HttpWebRequest req = WebRequest.Create(url) as HttpWebRequest;
            req.ContentType = "application/json";
            req.Headers.Add("Authorization", "Basic " + auto.basic64);
            req.Method = "GET";

            HttpWebResponse resp = req.GetResponse() as HttpWebResponse;
            string respuesta = resp.leer();
            JsonData jdata = JsonMapper.ToObject(respuesta);

            int total = (int) jdata["issues"].Count;

            List<Issue> issues = new List<Issue>();
            for (int i = 0; i < total; i++)
            {
                Issue issueX = new Issue();

                issueX.key      = jdata["issues"][i]["key"].ToString();
                issueX.summary  = jdata["issues"][i]["fields"]["summary"].ToString();
                issueX.status   = jdata["issues"][i]["fields"]["status"]["name"].ToString();
                issueX.priority = jdata["issues"][i]["fields"]["priority"]["name"].ToString();

                issues.Add(issueX);
            }

            return issues;
        }
    }
}
